/**
 * Copyright (c) 2018, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.consumer.config;

import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson.JSONObject;

import cn.waleychain.exchange.core.entity.ExceptionInfo;
import cn.waleychain.exchange.core.exec.ClientException;
import cn.waleychain.exchange.core.exec.NotFoundDataException;
import cn.waleychain.exchange.core.result.RetResultCode;
import cn.waleychain.exchange.core.utils.StringUtils;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;

/**
 * feign 请求返回异常重新定义
 * @author chenx
 * @date 2018年4月13日 下午5:31:52
 * @version 1.0 
 */
@Configuration
public class ExceptionErrorDecoder implements ErrorDecoder {

	@SuppressWarnings("rawtypes")
	@Override
	public Exception decode(String methodKey, Response response) {

		try {
			if (response.body() != null) {
				String body = Util.toString(response.body().asReader());
				ExceptionInfo ei = JSONObject.parseObject(body, ExceptionInfo.class);
				Class clazz = Class.forName(ei.getException());
				Object obj = clazz.newInstance();
				String message = ei.getMessage();
				int code = ei.getStatus();
				if (StringUtils.isNotBlank(message) && message.indexOf(":") != -1) {
					code = Integer.parseInt(message.substring(0, message.indexOf(":")));
					message = message.substring(message.indexOf(":") + 1);
				}
				if (obj instanceof ClientException) {
					if (code == 500 || code == 400 || code == 403) {
						return new ClientException(RetResultCode.E11001.getRet_code(), message);
					}
					
					return new ClientException(code, message);
				} else if (obj instanceof NotFoundDataException) {
					if (code == 500 || code == 400 || code == 403) {
						return new NotFoundDataException(RetResultCode.E13001.getRet_code(), message);
					}
					
					return new NotFoundDataException(code, message);
				} else {
					
					return new ClientException(code, message);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return new Exception("系统异常,请联系管理员");

	}

}
